﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using SharedComponents;

namespace OurLeague.Object
{
    public class Event
    {
        #region Fields

        String _id;
        int _type;
        int _minute;
        int _half;
        String _matchId;
        Player _player;
        String _lineUpPlayerId;

        public static List<Event> Events = new List<Event>();

        #endregion

        #region Constructors

        /*
        public Event(String str, int a, String str2)
        {

        }
        */

        public Event() { }

        #endregion

        #region Public Methods

        public void delete()
        {
            MySqlQueryHelper.deleteQuery(MySqlManager.Connection, "Events", "eventId", new String[] { Id });
            Events.Remove(this);
        }

        public void save()
        {
            MySqlRecord updateRecord = new MySqlRecord();

            updateRecord["half"] = Half;
            updateRecord["time"] = Minute;
            updateRecord["fkLineUp_PlayerId"] = LineUpPlayerId;
            updateRecord["fkEventTypeId"] = Type;
            updateRecord["fkMatchId"] = MatchId;

            if (!Events.Exists(e => e.Id == Id))
            {
                Events.Add(this);
                Id = MySqlQueryHelper.saveQuery(MySqlManager.Connection, "Events", null, updateRecord).ToString();

                return;
            }

            MySqlQueryHelper.saveQuery(MySqlManager.Connection, "Events", "eventId=" + Id, updateRecord);
        }

        public String getLineUpPlayerId(String lineUpId)
        {
            MySqlRecordset rs = MySqlQueryHelper.selectQuery(MySqlManager.Connection, "LineUps_Players", null, "fkLineUpId = " + lineUpId + " and fkPlayerId = " + Player.Id);
            return rs[0]["lineUp_PlayerId"].ToString();
        }

        /*
        public void update(String str)
        {

        }

        public void isGoal()
        {

        }

        public int comeInMinute(String str)
        {
            return 0;
        }

        public int comeOutMinute(String str)
        {
            return 0;
        }
        */
        #endregion

        #region Properties

        public String Id
        {
            get { return _id; }
            set { _id = value; }
        }

        public System.Drawing.Image EventTypeImage
        {
            get { return getEventTypeIcon(Type); }
        }

        public String LineUpPlayerId
        {
            get { return _lineUpPlayerId; }
            set { _lineUpPlayerId = value; }
        }

        public String MatchId
        {
            get { return _matchId; }
            set { _matchId = value; }
        }

        public int Type
        {
            get { return _type; }
            set { _type = value; }
        }

        public int Minute
        {
            get { return _minute; }
            set { _minute = value; }
        }

        public int Half
        {
            get { return _half; }
            set { _half = value; }
        }

        public Player Player
        {
            get { return _player; }
            set { _player = value; }
        }

        public String TeamName
        {
            get { return _player.TeamName; }
        }

        public String PlayerName
        {
            get { return _player.Surname + " " + _player.Name; }
        }

        public String PlayerNameAndTeam
        {
            get { return _player.Surname + " " + _player.Name.Substring(0, 1)+". ("+_player.TeamName+")"; }
        }

        public String Time
        {
            get { return Minute + "° " + Half + "T"; }
        }

        public String Description
        {
            get { return EventType.load(Type.ToString()).Name; }
        }

        #endregion

        #region Static Methods

        public static Event load(String idEvent)
        {
            Event eventToLoad = Events.Find(e => e._id == idEvent);
            if (eventToLoad == null)
            {
                eventToLoad = new Event();
                var eventRecord = MySqlQueryHelper
                    .selectQuery(MySqlManager.Connection, "Events", null, "eventId='" + idEvent + "'")[0];

                eventToLoad = addNewEvent(eventRecord);
            }

            return eventToLoad;
        }

        public static void removeAll(Match m)
        {
            Events.RemoveAll(e => m.Id == e.MatchId);
        }

        public static void loadAll(String id, String recordKey, String column)
        {
            var eventRecords = MySqlQueryHelper
                    .selectQuery(MySqlManager.Connection, "Events", null, column + "='" + id + "'");
            
            foreach (MySqlRecord eventRecord in eventRecords)
            {
                if (!Events.Exists(e => e.Id == eventRecord[recordKey].ToString()))
                    addNewEvent(eventRecord);
            }
        }
        
        public static void loadAll(Match m)
        {
            loadAll(m.Id, "eventId", "fkMatchId");
        }

        private static Event addNewEvent(MySqlRecord eventRecord)
        {
            Event eventObj = new Event();

            eventObj.Id = eventRecord["eventId"].ToString();
            eventObj.Half = int.Parse(eventRecord["half"].ToString());
            eventObj.Minute = int.Parse(eventRecord["time"].ToString());
            eventObj.LineUpPlayerId = eventRecord["fkLineUp_PlayerId"].ToString();
            eventObj.Player = getEventPlayer(eventObj.LineUpPlayerId);
            eventObj.Type = int.Parse(eventRecord["fkEventTypeId"].ToString());
            eventObj.MatchId = eventRecord["fkMatchId"].ToString();

            Events.Add(eventObj);

            return eventObj;
        }

        public static void loadAll(String teamId)
        {
            Team team = Team.load(teamId);
            var lineUpRecords = MySqlQueryHelper
                    .selectQuery(MySqlManager.Connection, "LineUps", null, "fkTeamId='" + teamId + "'");

            foreach (MySqlRecord lineUpRecord in lineUpRecords)
            {
                var lineups_players = MySqlQueryHelper
                    .selectQuery(MySqlManager.Connection, "LineUps_Players", null, "fkLineUpId='" + lineUpRecord["lineUpId"].ToString() + "'");
                foreach (MySqlRecord lineup_player in lineups_players)
                {
                    var events = MySqlQueryHelper
                        .selectQuery(MySqlManager.Connection, "Events", null, "fkLineUp_PlayerId='" + lineup_player["lineUp_PlayerId"] + "'");
                    foreach (MySqlRecord eventToLoad in events)
                        if (!Events.Exists(e => e.Id == eventToLoad["eventId"].ToString()))
                            addNewEvent(eventToLoad);
                }
            }
        }

        public static void loadAll()
        {
            var events = MySqlQueryHelper
                        .selectQuery(MySqlManager.Connection, "Events", null, null);
            foreach (MySqlRecord eventToLoad in events)
                if (!Events.Exists(e => e.Id == eventToLoad["eventId"].ToString()))
                    addNewEvent(eventToLoad);
        }

        private static Player getEventPlayer(String fkLineUps_PlayerId)
        {
            return Player.load(MySqlQueryHelper.selectQuery(MySqlManager.Connection, "LineUps_Players", new String[] { "fkPlayerId" }, "lineUp_PlayerId='" + fkLineUps_PlayerId + "'")[0]["fkPlayerId"].ToString());
        }

        /// <summary>
        /// Minuto dell'ultimo evento inserito
        /// </summary>
        /// <param name="idMatch">id della partita</param>
        /// <returns>minuto dell'evento +100 se secondo tempo. 0 se non esiste</returns>
        public static int lastEvent (string idMatch)
        {

            if (!Events.Exists(e=> e.MatchId==idMatch))
                return 0;
            if ((Events.OrderByDescending(e => e.Minute).OrderByDescending(e => e.Half).First(e => e.MatchId == idMatch).Half) == 2)
                return 100 + Events.OrderByDescending(e => e.Minute).OrderByDescending(e => e.Half).First(e => e.MatchId == idMatch).Minute;
            return Events.OrderByDescending(e => e.Minute).OrderByDescending(e => e.Half).First(e => e.MatchId == idMatch).Minute;

            /*String[] result = new String[2];
            result[0]= Events.OrderByDescending(e => int.Parse(e.Minute)).OrderByDescending(e => e.Half).First(e => e.MatchId == idMatch).Half;
            result[1] = Events.OrderByDescending(e => int.Parse(e.Minute)).OrderByDescending(e => e.Half).First(e => e.MatchId == idMatch).Minute;
            return result;*/
        }

        public static System.Drawing.Image getEventTypeIcon(int eventType)
        {
            switch (eventType)
            {
                case 1:
                    return OurLeague.Properties.Resources.gol;
                case 2:
                    return OurLeague.Properties.Resources.yellow2;
                case 3:
                    return OurLeague.Properties.Resources.red2;
                case 4:
                    return OurLeague.Properties.Resources.substitutionIn;
                case 5:
                    return OurLeague.Properties.Resources.substitutionOut;
                case 6:
                    return OurLeague.Properties.Resources.injury2;
                case 7:
                    return OurLeague.Properties.Resources.disallowGoal;
                case 8:
                    return OurLeague.Properties.Resources.penalty2;

                default:
                    return null;
            }
        }

        #endregion
    }

    #region Support Class

    public class EventType
    {
        String _id;
        String _name;
        String _url;

        public static List<EventType> EventTypes = new List<EventType>();

        public EventType()
        { }

        public static void loadAll()
        {
            var eventTypeRecords = MySqlQueryHelper
                    .selectQuery(MySqlManager.Connection, "EventTypes", null, null);

            foreach (MySqlRecord eventTypeRecord in eventTypeRecords)
            {
                if (!EventTypes.Exists(et => et.Id == eventTypeRecord["eventTypeId"].ToString()))
                    addNewEventType(eventTypeRecord);
            }
        }

        private static EventType addNewEventType(MySqlRecord eventTypeRecord)
        {
            EventType eventType = new EventType();

            eventType.Id = eventTypeRecord["eventTypeId"].ToString();
            eventType.Name = eventTypeRecord["name"].ToString();
            eventType.Url = eventTypeRecord["url"].ToString();

            EventTypes.Add(eventType);

            return eventType;
        }

        public static EventType load(String eventTypeId)
        {
            EventType eventTypeToLoad = EventTypes.Find(e => e._id == eventTypeId);

            if (eventTypeToLoad == null)
            {
                var eventTypeRecord = MySqlQueryHelper
                    .selectQuery(MySqlManager.Connection, "EventTypes", null, "eventTypeId='" + eventTypeId + "'")[0];

                eventTypeToLoad = addNewEventType(eventTypeRecord);
            }

            return eventTypeToLoad;
        }

        public String Id
        {
            get { return _id; }
            set { _id = value; }
        }

        public String Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public String Url
        {
            get { return _url; }
            set { _url = value; }
        }
    }

    #endregion
}
